package com.fzfnn.scrapbook.service.impl;

import com.fzfnn.scrapbook.entity.Comment;
import com.fzfnn.scrapbook.mapper.CommentMapper;
import com.fzfnn.scrapbook.service.CommentService;
import com.fzfnn.scrapbook.util.R;
import com.fzfnn.scrapbook.vo.CommentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private RedisTemplate<String, String> redisMail;

    @Override
    public R addComment(Comment comment , String token) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }
        comment.setUserId(Long.parseLong(userId));
        int result = commentMapper.addComment(comment);
        return result > 0 ? R.successMsg("评论成功") : R.errorMsg("评论失败");
    }

    @Override
    public R getCommentsByJournalId(Long journalId) {
        List<Comment> list = commentMapper.getCommentsByJournalId(journalId);
        return R.successData(list);
    }

    @Override
    public R deleteComment(Long commentId, String token) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }
        long userIds = Long.parseLong(userId);
        int result = commentMapper.deleteComment(commentId, userIds);
        return result > 0 ? R.successMsg("删除成功") : R.errorMsg("删除失败或无权限");
    }

    @Override
    public R getNestedCommentsByJournalId(Long journalId) {
        List<CommentVO> allComments = commentMapper.selectCommentsByJournalId(journalId);
        Map<Long, CommentVO> commentMap = new HashMap<>();
        List<CommentVO> rootComments = new ArrayList<>();

        for (CommentVO commentVO : allComments) {
            commentVO.setReplies(new ArrayList<>());
            commentMap.put(commentVO.getCommentId(), commentVO);
        }

        for (CommentVO commentVO : allComments) {
            Long parentId = commentVO.getParentId();
            if (parentId == null) {
                rootComments.add(commentVO);
            } else {
                CommentVO parent = commentMap.get(parentId);
                if (parent != null) {
                    parent.getReplies().add(commentVO);
                }
            }
        }

        return R.successData(rootComments);
    }
}
